package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusRequest;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusResponse;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusResponseBody;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.dto.DeviceDataListDto;
import com.zzyl.nursing.dto.MemberUserDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataListVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-09
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;
    @Autowired
    private Client client;

    @Autowired
    private DeviceDataMapper deviceDataMapper;
    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    /**
     * 小程序登录方法
     *
     * @param userLoginRequestDto 请求数据
     * @return 登录结果，包含token和nickname
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用微信官方接口获取openId
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        // 2.根据openId查询数据库获取用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openId));

        // 3.如果用户信息不存在，就创建一个用户，并绑定openId
        if (ObjectUtils.isEmpty(familyMember)) {
            // 新用户
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }

        // 4.调用微信接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        // 不论是新用户还是老用户，都更新手机号
        familyMember.setPhone(phoneNumber);

        // 5.保存或更新用户，如果是新增，要生成一个用户名
        saveOrUpdateFamilyMember(familyMember);

        // 6.封装用户信息到token中，返回给小程序
        LoginVo loginVo = new LoginVo();
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        // 返回结果
        return loginVo;
    }

    /**
     * 新增或更新老人家属
     * @param familyMember  老人家属对象
     */
    private void saveOrUpdateFamilyMember(FamilyMember familyMember) {
        // 判断id是否为空
        if (ObjectUtils.isEmpty(familyMember.getId())) {
            // 新增
            // 生成一个随机的用户名，规则是：一个随机的好听的名字+手机号后4位
            String prefix = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()));
            String nickName = prefix + familyMember.getPhone().substring(7);
            familyMember.setName(nickName);
            familyMemberMapper.insert(familyMember);
        } else {
            // 更新
            familyMemberMapper.updateById(familyMember);
        }
    }

    /**
     * 小程序端绑定家人
     *
     * @param memberUserDto
     */
    @Override
    public void bindFamilyMember(MemberUserDto memberUserDto) {
        //拿到userId
        Long userId = UserThreadLocal.getUserId();
        //根据身份证号查询老人
        Elder elder = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, memberUserDto.getIdCard()));
        //若没查到，则返回
        if(ObjectUtil.isEmpty(elder)){
            throw new BaseException("未查询到该老人信息");
        }
        //若查到了，根据身份证号查询姓名是否一致
        String elderName = elder.getName();
        String name = memberUserDto.getName();
        //若不一致，报错
        if(!name.equals(elderName)){
            throw new BaseException("该老人信息与身份证号不匹配");
        }
        //若一致，则新增数据到中间表里面
        LocalDateTime now = LocalDateTime.now();
        familyMemberMapper.bindFamilyMember(userId, elder.getId(),memberUserDto.getRemark(),now);
    }

    /**
     * 小程序端获取家人列表
     */
    @Override
    public List<MemberUserVo> getMyFamilyMemberList() {
        Long userId = UserThreadLocal.getUserId();
        List<MemberUserVo> memberUserVos=familyMemberMapper.getMyFamilyMemberList(userId);
        return memberUserVos;
    }

    /**
     * 小程序端查看已绑定家人列表（分页查询）
     *
     * @param pageNum
     * @param pageSize
     */
    @Override
    public List<MemberUserPageVo> getMyFamilyMemberListByPage(Integer pageNum, Integer pageSize) {
        Page<FamilyMember> page = new Page<>(pageNum,pageSize);
        page = page(page);
        Long userId = UserThreadLocal.getUserId();
        List<MemberUserPageVo> memberUserPageVos =familyMemberMapper.getMyFamilyMemberListByPage(userId);
        return memberUserPageVos;
    }


    /**
     * 小程序端查询健康数据
     *
     * @param request
     */
    @Override
    public AjaxResult QueryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("调用IOT平台查询失败");
        }
        if(!response.body.getSuccess()){
            throw new BaseException("调用IOT平台查询失败");
        }
        QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyData data = response.body.data;
        return AjaxResult.success(data);
    }

    @Override
    public List<DeviceDataListVo> queryDeviceDataListByDay(DeviceDataListDto deviceDataListDto) {
        List<DeviceDataListVo> list = new ArrayList<>();

        String iotId = deviceDataListDto.getIotId();
        String functionId = deviceDataListDto.getFunctionId();
        Long startTime = deviceDataListDto.getStartTime();
        Long endTime = deviceDataListDto.getEndTime();

        for (int i = 0; i < 24; i++) {
            DeviceDataListVo deviceDataListVo = new DeviceDataListVo();
            Long hour = startTime + (i*3600000);
            Long hour1 = hour+ 3600000;
            LocalDateTime localDateTime = LocalDateTimeUtil.of(hour);
            LocalDateTime localDateTime1 = LocalDateTimeUtil.of(hour1);

            if (hour1>endTime){
                break;
            }
            if (i>=10){
                deviceDataListVo.setDateTime(i+":00");
                Long value=  deviceDataMapper.queryDeviceDataListByDay(iotId,functionId,localDateTime,localDateTime1);
                if (ObjectUtil.isEmpty(value)){
                    deviceDataListVo.setDataValue(0.0);
                }else {
                    deviceDataListVo.setDataValue(value.doubleValue());
                }
                list.add(deviceDataListVo);

            }else {
                deviceDataListVo.setDateTime("0"+i+":00");
                Long value=  deviceDataMapper.queryDeviceDataListByDay(iotId,functionId,localDateTime,localDateTime1);
                if (ObjectUtil.isEmpty(value)){
                    deviceDataListVo.setDataValue(0.0);
                }else {
                    deviceDataListVo.setDataValue(value.doubleValue());
                }
                list.add(deviceDataListVo);
            }
        }
        return list;
    }

    @Override
    public List<DeviceDataListVo> queryDeviceDataListByWeek(DeviceDataListDto deviceDataListDto) {
        List<DeviceDataListVo> list = new ArrayList<>();

        String iotId = deviceDataListDto.getIotId();
        String functionId = deviceDataListDto.getFunctionId();
        Long startTime = deviceDataListDto.getStartTime();
        Long endTime = deviceDataListDto.getEndTime();
        for (int i = 0; i < 7; i++) {
            DeviceDataListVo deviceDataListVo = new DeviceDataListVo();
            Long day = startTime + (i*86400000);
            Long day1 = day+ 86400000-1;

            LocalDateTime localDateTime = LocalDateTimeUtil.of(day);
            LocalDateTime localDateTime1 = LocalDateTimeUtil.of(day1);

            if (day1>endTime){
                break;
            }

            // 定义输出的格式
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM.dd");

            // 格式化 LocalDate 对象为所需格式
            String formattedDate = localDateTime.toLocalDate().format(outputFormatter);
            deviceDataListVo.setDateTime(formattedDate);

            Long value=  deviceDataMapper.queryDeviceDataListByDay(iotId,functionId,localDateTime,localDateTime1);
            if (ObjectUtil.isEmpty(value)){
                deviceDataListVo.setDataValue(0.0);
            }else {
                deviceDataListVo.setDataValue(value.doubleValue());
            }
            list.add(deviceDataListVo);

        }

        return list;
    }
}
